﻿using Coldairarrow.Entity;
using Coldairarrow.Entity.Base_Manage;
using Coldairarrow.Entity.DTO;
using Coldairarrow.Util;
using EFCore.Sharding;
using LinqKit;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Coldairarrow.Business.Base_Manage
{
    class PermissionBusiness : BaseBusiness<Base_Action>, IPermissionBusiness, ITransientDependency
    {
        public PermissionBusiness(IDbAccessor db, IBase_ActionBusiness actionBus, IBase_UserBusiness userBus)
            : base(db)
        {
            _actionBus = actionBus;
            _userBus = userBus;
        }
        IBase_ActionBusiness _actionBus { get; }
        IBase_UserBusiness _userBus { get; }

        async Task<string[]> GetUserActionIds(string userId)
        {
            var where = LinqHelper.False<Base_Action>();
            var theUser = await _userBus.GetTheDataAsync(userId);

            //不需要权限的菜单
            where = where.Or(x => x.NeedAction == false);

            if (userId == GlobalData.ADMINID || theUser.RoleType.HasFlag(RoleTypes.超级管理员))
                where = where.Or(x => true);
            else
            {
                var actionIds = from a in Db.GetIQueryable<Base_UserRole>()
                                join b in Db.GetIQueryable<Base_RoleAction>() on a.RoleId equals b.RoleId
                                where a.UserId == userId
                                select b.ActionId;

                where = where.Or(x => actionIds.Contains(x.Id));
            }

            return await GetIQueryable().Where(where).Select(x => x.Id).ToArrayAsync();
        }

        public async Task<List<Base_ActionDTO>> GetUserMenuListAsync(string userId)
        {
            var actionIds = await GetUserActionIds(userId);
            return await _actionBus.GetTreeDataListAsync(new Base_ActionsInputDTO
            {
                types = new ActionType[] { ActionType.菜单, ActionType.页面 },
                ActionIds = actionIds,
                checkEmptyChildren = true
            });
        }

        public async Task<List<string>> GetUserPermissionValuesAsync(string userId)
        {
            var actionIds = await GetUserActionIds(userId);
            return (await _actionBus
                .GetDataListAsync(new Base_ActionsInputDTO
                {
                    types = new ActionType[] { ActionType.权限 },
                    ActionIds = actionIds
                }))
                .Select(x => x.Value)
                .ToList();
        }


        public async Task<List<DingUser>> ChkDingdingUserIdAsync(DingLoginInputDTO input)
        {
            //先查看当前用户是否已绑定钉钉账号
            var theUser = await Db.GetIQueryable<Base_User>().FirstOrDefaultAsync(x => x.DingUserId.Equals(input.userId));
            if (!theUser.IsNullOrEmpty())
            {
                //已绑定
                //生成token,有效期一天
                JWTPayload jWTPayload = new JWTPayload
                {
                    UserId = theUser.Id,
                    Expire = DateTime.Now.AddDays(1)
                };
                string token = JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);
                throw new BusException(token,666);
            }
            else
            {
                //未绑定
                #region sql语句
                StringBuilder sql = new StringBuilder();
                sql.Append("SELECT ");
                sql.Append("a.Id,");
                sql.Append("a.RealName,");
                sql.Append("a.UserPost,");
                sql.Append("c.Name Factory,");
                sql.Append("b.Name Department ");
                sql.Append("FROM ");
                sql.Append("Base_User a ");
                sql.Append("LEFT JOIN Base_Department b on a.DepartmentId=b.Id ");
                sql.Append("LEFT JOIN Base_Department c on a.FactoryId=c.Id ");
                sql.Append("WHERE ");
                sql.Append("a.RealName='"+input.userName+"'");
                #endregion
                var users = await Db.GetListBySqlAsync<DingUser>(sql.ToString());
                return users;
            }
        }

        public async Task<string> SetDingdingUserIdAsync(DingBindInputDTO input) 
        {
            string sql = "UPDATE Base_User SET DingUserId='"+input.dingId+"' WHERE Id='"+input.userId+"'";
            int result = await Db.ExecuteSqlAsync(sql);
            if (result > 0) 
            {
                JWTPayload jWTPayload = new JWTPayload
                {
                    UserId = input.userId,
                    Expire = DateTime.Now.AddDays(1)
                };
                return JWTHelper.GetToken(jWTPayload.ToJson(), JWTHelper.JWTSecret);
            } 
            else 
            {
                return "";
            }
        }
    }
}
